package com.ebix.sample.dao;

import static com.ebix.sample.dao.helper.DAOHelper.INSTANCE;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javax.naming.NamingException;

import com.ebix.sample.excetion.WisException;
import com.ebix.sample.to.CorretorTO;
import com.ebix.sample.to.UserTO;

public class AdminDAO {

	private static ResourceBundle b = ResourceBundle//
			.getBundle("com.ebix.sample.dao.AdminDAO");

	public UserTO findUser(UserTO user) throws WisException {
		Connection con = null;
		PreparedStatement ps = null, ps2 = null;
		ResultSet rs = null, rs2 = null;
		try {
			con = INSTANCE.getConnection();
			ps = con.prepareStatement(b.getString("select-user"));
			// in the real app we don't send the password, but the md5 hash
			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPassword());
			rs = ps.executeQuery();
			if (rs.next()) {
				user.setId(rs.getInt(1));
				user.setTheme(rs.getString(2));
			} else
				throw new WisException("Invalid username or password");
			//now we recover the associated broker
			ps2 = con.prepareStatement(b.getString("select-broker"));
			ps2.setInt(1, user.getId());
			rs2 = ps2.executeQuery();
			if (rs2.next()) 
				user.setCorretor(new CorretorTO(rs.getInt(1), rs.getString(2)));
			return user;
		} catch (NamingException e) {
			throw new WisException(e);
		} catch (SQLException e) {
			throw new WisException(e);
		} finally {
			INSTANCE.close(ps2, rs2);
			INSTANCE.close(con, ps, rs);
		}
	}
}
